package com.example.spring_start.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.pojo.article;
import com.example.req.articleByIdReq;
import com.example.req.articleReq;
import com.example.req.articleSaveReq;
import com.example.resp.PageResp;
import com.example.spring_start.mapper.articleMapper;
import com.example.utils.CopyUtil;
import com.example.utils.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.security.PublicKey;

@Service
public class articleServiceImpl extends ServiceImpl<articleMapper, article> implements articleService{
    @Resource
    private articleMapper articleMapper;

    @Resource
    SnowFlake snowFlake;

    @Override
    public PageResp<article> getarticleList(articleReq articleReq){
        QueryWrapper<article> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(articleReq.getArticlename())){
            queryWrapper.lambda().eq(article::getArticlename,articleReq.getArticlename());
        }
        if (!ObjectUtils.isEmpty(articleReq.getArticleuser())){
            queryWrapper.lambda().eq(article::getArticleuser,articleReq.getArticleuser());
        }
        Page<article> page = new Page<>(articleReq.getPage(),articleReq.getSize());
        IPage<article> articleIPage = articleMapper.selectPage(page,queryWrapper);
        PageResp<article> pageResp = new PageResp<>();
        pageResp.setTotal(articleIPage.getTotal());
        pageResp.setList(articleIPage.getRecords());
        return pageResp;
    }
    @Override
    public void savearticle(articleSaveReq req){
        article pojo = CopyUtil.copy(req, article.class);
        if (req.getArticleid() == 0){
            pojo.setArticleid(snowFlake.nextId());
            articleMapper.insert(pojo);
        }else {
            System.out.println(pojo);
            articleMapper.updateById(pojo);
        }
    }
    @Override
    public void deletearticle(Long articleid){
        articleMapper.deleteById(articleid);
    }

    @Override
    public article getarticleByID(Long articleid) {
        QueryWrapper<article> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(article::getArticleid, articleid);
        return articleMapper.selectOne(queryWrapper);
    }
}
